<template>
  <div class="container">
    <el-card>
      <h3 slot="header">添加商品</h3>
      <el-form :model="form" label-width="120px">
        <el-form-item label="商品名称：" prop="name">
          <el-input placeholder="请输入商品名称" v-model="form.name" />
        </el-form-item>
        <el-form-item label="商品分类：" prop="cat">
          <el-cascader size="medium" v-model="form.cat" :options="cats" />
        </el-form-item>
        <el-form-item label="商品数量：" prop="stock">
          <el-input-number v-model="form.stock" :min="1" :max="1000" label="商品数量" />
        </el-form-item>
        <el-form-item label="商品价格：" prop="originalPrice">
          <el-input placeholder="请输入价格" v-model="form.originalPrice" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="实际价格：" prop="price">
          <el-input placeholder="请输入实际价格" v-model="form.price" type="number">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="所在城市：" prop="price">
          <el-input placeholder="请输入城市名称" v-model="form.detailTitle">
          </el-input>
        </el-form-item>
        <el-form-item label="新旧程度：" prop="qualityLevel">
          <el-select v-model="form.qualityLevel" placeholder="请选择新旧程度">
            <el-option label="全新" value="全新" />
            <el-option label="五成新" value="五成新" />
            <el-option label="六成新" value="六成新" />
            <el-option label="七成新" value="七成新" />
            <el-option label="八成新" value="八成新" />
            <el-option label="九成新" value="九成新" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="所在城市：" prop="city">
          <el-input placeholder="请输入所在城市" v-model="form.city" />
        </el-form-item>-->
        <el-form-item label="商品图片：">
          <el-upload :disabled="bt_diable" :action="uploadUrl" multiple :on-success="onSuccess">
            <el-button :disabled="bt_diable" size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品介绍：" prop="description">
          <el-input placeholder="请输入商品介绍" v-model="form.description" type="textarea" rows="5" />
        </el-form-item>
        <el-form-item label>
          <div class="btn-box">
            <el-button type="primary" @click="onSubmit">完成并发布</el-button>
            <!-- <el-button type="success">申请代卖</el-button> -->
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script >
  import { doCateList, doUpdate, doCreate } from '@/apis/product';
  import { uploadUrl } from '@/apis/common';

  export default {
    name: 'ProductsAdd',
    props: {
      modify: {
        Object,
        default: () => {}
      }
    },
    unData: {
      fileList: []
    },
    data() {
      return {
        update_flag: 0,
        cats: [],
        bt_diable: false,
        uploadUrl: uploadUrl,
        form: {
          name: '', // 商品名称
          cat: [], // 分类
          stock: 1, // 数量
          originalPrice: '', // 估价
          price: '', // 实际价格
          detailTitle: '',
          qualityLevel: '九成新',
          description: ''
        }
      };
    },

    methods: {

      async onSubmit() {
        const files = this.$options.unData.fileList.map(item => {
          return {
            id: item.response.data.files[0].id,
            pic: item.response.data.files[0].pic
          };
        });
        const user = this.cache.fetchUser();
        console.info(user);
        let data = {
          productParam: {
            name: this.form.name,
            stock: this.form.stock,
            originalPrice: parseInt(this.form.originalPrice),
            price: parseInt(this.form.price),
            detailTitle: this.form.detailTitle,
            description: this.form.description,
            productCategoryId: this.form.cat[1],
            productCategoryName: 'test',
            qualityLevel: this.form.qualityLevel,
            memberId : user.id
          },
          uploadResult: {
            files: files
          }
        };
        for (const cat_ins of this.cats) {
          for (const sub_ins of cat_ins.children) {
            if (sub_ins.value === data.productParam.productCategoryId) {
              data.productParam.productCategoryName = sub_ins.label;
            }
          }
        }
        // console.log(data);
        if (this.update_flag === 1) {
          data.productParam.id = this.$route.params.id;
        }
        data = {
          reqJson: JSON.stringify(data)
        };
        if (this.update_flag === 1) {
          await doUpdate(data);
        } else {
          console.log(data);
          await doCreate(data);
        }
        this.$router.push({ path: 'myproducts' });
      },

      onSuccess(response, file, fileList) {
        this.$options.unData.fileList = fileList;
        console.log(fileList);
      },
      async onFetchCats() {
        const res = await doCateList();
        let str = JSON.stringify(res.data);
        str = str
          .replace(/name/g, 'label')
          .replace(/items/g, 'children')
          .replace(/id/g, 'value');
        this.cats = JSON.parse(str);
      }
    },
    mounted() {
      this.onFetchCats();
      if (Object.prototype.hasOwnProperty.call(this.$route.params, 'id')) {
        this.bt_diable = true;
        this.form.name = this.$route.params.name;
        this.form.stock = this.$route.params.stock;
        this.form.originalPrice = this.$route.params.originalPrice;
        this.form.price = this.$route.params.price;
        this.form.detailTitle = this.$route.params.detailTitle;
        this.form.cat[1] = this.$route.params.productCategoryId;
        this.update_flag = 1;
      }
    },
    created() {}
  };
</script>
<style lang="scss" type="text/scss" scoped>
.el-card {
  width: 100%;
}
.el-input,
.el-cascader,
.el-select,
.el-textarea {
  width: 80%;
}
.btn-box {
  text-align: center;
  width: 80%;
  .el-button {
    margin: 0 15px;
  }
}
</style>
